package cn.jsl.shop.service.impl;

import cn.jsl.basic.dto.ShopDto;
import cn.jsl.basic.exception.MyException;
import cn.jsl.basic.service.impl.BaseServiceImpl;
import cn.jsl.basic.util.BaiduAuditUtils;
import cn.jsl.basic.util.MD5Utils;
import cn.jsl.basic.util.StrUtils;
import cn.jsl.emp.domain.Employee;
import cn.jsl.emp.mapper.EmployeeMapper;
import cn.jsl.logininfo.domain.Logininfo;
import cn.jsl.logininfo.mapper.LogininfoMapper;
import cn.jsl.shop.domain.Shop;
import cn.jsl.shop.domain.ShopAuditLog;
import cn.jsl.shop.mapper.ShopAuditLogMapper;
import cn.jsl.shop.mapper.ShopMapper;
import cn.jsl.shop.service.IShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImplShopService extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 店铺入驻
     */
    @Override
    public void settlement(Shop shop) {
        //空值校验
        if(StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getTel())
                || StringUtils.isEmpty(shop.getAddress()) || StringUtils.isEmpty(shop.getEmployee().getUsername())
                || StringUtils.isEmpty(shop.getEmployee().getEmail()) || StringUtils.isEmpty(shop.getEmployee().getPhone())
                || StringUtils.isEmpty(shop.getEmployee().getPassword())){
            throw new MyException("数据不能为空!");
        }
        //密码是否一致：不做，如果要做在t_employee加一个字段comfirmPassword

        //校验店铺的名字是否合规-要在查询数据库之前校验
        Boolean censor = BaiduAuditUtils.TextCensor(shop.getName());
        if (!censor){
            throw new MyException("店铺名字不合规,请重新输入!");
        }

        //是否入驻过
        Shop shopTmp = shopMapper.loadByMessage(shop);
        if(shopTmp != null){
            throw new MyException("已经入驻了,请直接登录!");
        }

        //添加到数据库
        //添加t_employee
        Employee employee = shop.getEmployee();
        //设置盐值 和 加密之后的密码
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        //保存logininfo信息
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        //保存员工信息
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);

        //添加t_shop
        shop.setAdmin_id(employee.getId());
        shopMapper.save(shop);

        //修改employee的shopId
        /*employee.setShopId(shop.getId());*/
        employee.setShop(shop);
        employeeMapper.update(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //设置为管理员
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void pass(ShopAuditLog log) throws MessagingException {
        //修改状态：state = 2
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        //添加审核日志到数据库
        //状态
        log.setState(2);
        //管理员
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);

        //发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("1509370299@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>你的店铺已经注册!</h1>" +
                "<img src='http://115.159.88.63:8800"+shop.getLogo()+"' >" +
                "<a href='http://localhost:8080/shop/active/"+shop.getId()+"'>点击该链接激活</a>",true);
        //设置收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("1509370299@qq.com");
        //发送
        javaMailSender.send(mimeMessage);

    }



    @Override
    public void reject(ShopAuditLog log) throws MessagingException {

        //添加审核日志到数据库
        log.setState(4);
        log.setAuditId(325L);
        shopAuditLogMapper.save(log);

        //发送邮件：驳回邮件 - 告诉他审核失败，重新入驻
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("1509370299@qq.com");
        //设置主题
        helper.setSubject("入驻失败邮件");
        //设置内容
        helper.setText("<h1>店铺入驻失败!</h1>" +
                "<a href='http://localhost:8081/register'>点击重新入驻</a>",true);
        //设置收件人
        Shop shop = shopMapper.loadById(log.getShopId());
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("1509370299@qq.com");
        //发送
        javaMailSender.send(mimeMessage);
        //删除管理员信息
        employeeMapper.delete(shop.getAdmin_id());
        //删除店铺信息
        shopMapper.delete(shop.getId());
    }

    /**
     * 获取每一个店铺状态的数量
     * @return
     */
    @Override
    public List<ShopDto> getShopState() {
        return shopMapper.getShopState();
    }

    /**
     * 邮箱激活功能
     * @param id
     * @param
     */
    @Override
    public void active(Long id) {
        Shop shop = shopMapper.loadById(id);
        shop.setState(3);
        shopMapper.update(shop);
    }
}
